<?php
namespace app\apijson\query\operators;

class LogicOperator
{
    public static function apply($query, $key, $value)
    {
        // 逻辑运算符支持
        if (preg_match('/^(\w+)([&|!])?\{\}$/', $key, $m)) {
            $field = $m[1];
            if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $field)) {
                throw new \app\apijson\core\ApiJsonException('非法逻辑字段: ' . $field);
            }
            $logic = $m[2] ?? '|'; // 默认 or
            
            if ($logic === '!') {
                // NOT IN
                if (is_array($value)) {
                    $query->whereNotIn($field, $value);
                } else {
                    foreach (explode(',', $value) as $cond) {
                        $cond = trim($cond);
                        if ($cond !== '') {
                            $query->where($field, '!=', $cond);
                        }
                    }
                }
            } elseif ($logic === '&') {
                // AND
                foreach (is_array($value) ? $value : explode(',', $value) as $cond) {
                    $cond = trim($cond);
                    if ($cond !== '') {
                        self::applyCondition($query, $field, $cond, 'and');
                    }
                }
            } else { // '|' or default
                $conds = is_array($value) ? $value : explode(',', $value);
                $query->where(function($q) use ($field, $conds) {
                    foreach ($conds as $cond) {
                        $cond = trim($cond);
                        if ($cond !== '') {
                            self::applyCondition($q, $field, $cond, 'or');
                        }
                    }
                });
            }
            return true;
        }
        
        return false;
    }

    protected static function applyCondition($query, $field, $cond, $logic = 'and')
    {
        // 支持 >=10, <=40, >10, <40, =10, 10
        if (preg_match('/^(>=|<=|>|<|=)?(.*)$/', $cond, $m)) {
            $op = $m[1] ?: '=';
            $val = $m[2];
            if ($logic === 'or') {
                $query->orWhere($field, $op, $val);
            } else {
                $query->where($field, $op, $val);
            }
        }
    }
} 